#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MAX_TEXT 512
#define MSG_KEY 1234

struct msgbuf {
    long mtype;
    char mtext[MAX_TEXT];
};

int main() {
    int msgid;
    struct msgbuf msg;

    // 获取已存在的消息队列
    msgid = msgget(MSG_KEY, 0666 | IPC_CREAT);
    if (msgid == -1) {
        perror("msgget failed");
        exit(EXIT_FAILURE);
    }

    printf("Waiting to receive messages...\n");
    while (1) {
        // 接收类型为1的消息（阻塞接收）
        if (msgrcv(msgid, &msg, MAX_TEXT, 1, 0) == -1) {
            perror("msgrcv failed");
            exit(EXIT_FAILURE);
        }

        // 如果收到 "exit"，退出循环
        if (strncmp(msg.mtext, "exit", 4) == 0) {
            printf("Received exit signal. Exiting.\n");
            break;
        }

        printf("Received: %s", msg.mtext);
    }

    // 删除消息队列
    if (msgctl(msgid, IPC_RMID, NULL) == -1) {
        perror("msgctl(IPC_RMID) failed");
        exit(EXIT_FAILURE);
    }

    return 0;
}
